package com.ruoyi.system.service.impl;

import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NameUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.dto.XsUserDto;
import com.ruoyi.system.domain.vo.user.XsUserVo;
import com.ruoyi.system.domain.vo.user.XsUserInfoVo;
import com.ruoyi.system.domain.xs.XsUser;
import com.ruoyi.system.mapper.XsUserMapper;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IXsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author 97099
* @description 针对表【xs_user(用户表)】的数据库操作Service实现
* @createDate 2025-01-07 14:05:56
*/
@Service
public class XsUserServiceImpl extends ServiceImpl<XsUserMapper, XsUser>
implements IXsUserService {

    @Autowired
    private XsUserMapper xsUserMapper;

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public List<XsUserVo> selectXsUserList(XsUserDto userDto) {
        return xsUserMapper.selectXsUserList(userDto);
    }

    @Override
    @Transactional
    public String add(XsUserDto userDto) {

        // 校验手机号/密码格式是否正常
        // 判断 手机号 是否已注册
        SysUser user = new SysUser();
        user.setPhonenumber(userDto.getPhonenumber());
        if (StringUtils.isNotEmpty(sysUserService.selectUserList(user))) {
            throw new GlobalException("该手机号已注册");
        }
        // 未输入用户名 使用随机用户名
        String userName = StringUtils.isEmpty(userDto.getUserName()) ? NameUtil.getUserName(6) : user.getUserName();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        sysUser.setNickName(StringUtils.isEmpty(userDto.getNickName()) ? NameUtil.getName() : userDto.getNickName());
        sysUser.setPhonenumber(userDto.getPhonenumber());
        sysUser.setPassword(SecurityUtils.encryptPassword(userDto.getPassword()));
        sysUser.setRoleIds(new Long[]{userDto.getRoleId()});
        sysUser.setUserType("00");
        sysUserService.insertUser(sysUser);
        addUser(userDto, sysUser.getUserId());
        return userName;
    }

    /**
     * 新增用户
     * @param userDto
     * @param sysUserId
     * @return
     */
    @Transactional
    public void addUser(XsUserDto userDto, Long sysUserId) {
        XsUser xsUser = new XsUser();
        xsUser.setSysUserId(sysUserId);
        xsUser.setPhonenumber(userDto.getPhonenumber());
        if (userDto.getRoleId() == 101L || userDto.getRoleId() == 102L) {
            if (StringUtils.isEmpty(userDto.getRealName())) {
                throw new GlobalException("请输入真实姓名");
            }
            xsUser.setRealName(userDto.getRealName());
            String PJ = PinyinUtil.getFirstLetter(userDto.getRealName(),"");
            xsUser.setUserCode(NameUtil.getUserCode(3, PJ.toUpperCase(), sysUserId)); //TODO 随机数，后续需修改为自选
        }
        xsUser.setCreateTime(DateUtils.getNowDate());
        xsUser.setRemark(userDto.getRoleId() == 101L ? "写手" : userDto.getRoleId() == 102L ? "客服" : "普通用户");
        if (!save(xsUser)) {
            throw new GlobalException("注册用户失败！");
        }
    }

    /**
     * 禁用用户（可批量）
     * @param ids
     * @return
     */
    @Override
    public int disableUser(Long[] ids) {
        return xsUserMapper.disableUser(ids, "1");
    }

    /**
     * 用户详情
     * @param id
     * @return
     */
    @Override
    public XsUserInfoVo getUserInfo(Long id) {
        return xsUserMapper.getUserInfo(id);
    }

    /**
     * 修改用户
     * @param xsUserDto
     * @return
     */
    @Override
    @Transactional
    public boolean updateXsUser(XsUserDto xsUserDto) {

        XsUser xsUser = lambdaQuery().eq(XsUser::getId, xsUserDto.getId()).one();
        if (StringUtils.isNull(xsUser)) {
            throw new GlobalException("用户异常！");
        }
        SysUser user = new SysUser();
        user.setPhonenumber(xsUserDto.getPhonenumber());
        if (!xsUserDto.getPhonenumber().equals(xsUser.getPhonenumber()) && StringUtils.isNotEmpty(sysUserService.selectUserList(user))) {
            throw new GlobalException("该手机号已注册");
        }
        if (StringUtils.isNotEmpty(xsUserDto.getNickName())
                || StringUtils.isNotEmpty(xsUserDto.getUserName())
                || StringUtils.isNotEmpty(xsUserDto.getPhonenumber())) {
            // 修改系统用户表
            SysUser sysUser = new SysUser();
            sysUser.setUserId(xsUser.getSysUserId());
            sysUser.setUserName(xsUserDto.getUserName());
            sysUser.setPhonenumber(xsUserDto.getPhonenumber());
            sysUser.setNickName(xsUserDto.getNickName());
            sysUser.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
            sysUserService.updateUser(sysUser);
        }
        return lambdaUpdate().set(XsUser::getRealName, xsUserDto.getRealName())
                .set(StringUtils.isNotEmpty(xsUserDto.getPhonenumber()), XsUser::getPhonenumber, xsUserDto.getPhonenumber())
                .set(XsUser::getSkills, xsUserDto.getSkills())
                .set(XsUser::getWillingness, xsUserDto.getWillingness())
                .set(XsUser::getUpdateBy, SecurityUtils.getUserId())
                .set(XsUser::getUpdateTime, DateUtils.getNowDate())
                .eq(XsUser::getId, xsUserDto.getId()).update();
    }
}
